package com.ht.module.common.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ht.abnormal.HtException;
import com.ht.constant.DicConstants;
import com.ht.module.common.dto.UpdateStateDto;
import com.ht.module.common.mapper.CommonMapper;
import com.ht.module.common.service.CommonService;
import com.ht.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @ProjectName: ht
 * @ClassName: CommonServiceImpl
 * @Author: hejialun
 * @Description: 公共类实现类
 * @Date: 2021/9/14 16:14
 */
@Service
public class CommonServiceImpl implements CommonService {
    @Value("${upload.path}")
    private String tempPath;
    @Value("${upload.prefix}")
    private String prefix;
    @Override
    public String uploadFile(MultipartFile file) {
        //判断文件是否存在
        if(null==file){
            throw new HtException("文件不存在!");
        }
        String date= DateUtil.getDate();

        //判断当前文件夹是否存在
        if (!new File(tempPath+prefix+date).exists()) {
            new File(tempPath+prefix+date).mkdirs();
        }
        //重命名文件
        String filePath=prefix+date+"/"+ UUID.randomUUID().toString()+"_"+file.getOriginalFilename();

        try{
            file.transferTo(new File(tempPath+filePath));
        }catch (Exception e){
            throw new HtException(e.getMessage());
        }
        return  filePath;
    }

    @Override
    public Boolean delFile(String path) {
        File file = new File(tempPath+path);
        if (file.exists() && file.isFile()) {
            //文件存在
            if (file.delete()) {
                //删除成功
                return true;
            } else {
                throw new HtException("删除文件失败！");
            }
        } else {
            throw new HtException("文件不存在！");
        }
    }
}